/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin			*/
/*	Project:	GlbCloud			*/
/*	Author:		gong_libin			*/
/*	Date:		2012_01_09			*/
/*	File:		MrNet.cpp			*/
/********************************************************/

#include "MrNet.h"

CMrNet::CMrNet()
{
	m_iSocket = MR_FAILURE;
}

CMrNet::~CMrNet()
{
	m_iSocket = MR_FAILURE;
}

int CMrNet::MrNetOpen(int iType)
{
	m_iSocket = socket(AF_INET, iType, 0);
	if (m_iSocket < 0) {
		MR_ERROR("%s\n", strerror(errno));
		return MR_FAILURE;
	}

	return MR_SUCCESS;
}

void CMrNet::MrNetClose()
{
	if (m_iSocket > 0) {
		close(m_iSocket);
		m_iSocket = MR_FAILURE;
	}

	return;
}

int CMrNet::MrNetGetSocket()
{
	return m_iSocket;
}

void CMrNet::MrNetSetSocket(int iSocket)
{
	m_iSocket = iSocket;
}

char* CMrNet::MrNetUrl(char* pszUrl)
{
	while('\0' != *pszUrl && ':' != *pszUrl) pszUrl ++;
	*pszUrl ++ = '\0';

	return '\0' != *pszUrl ? pszUrl : NULL;
}

int CMrNet::MrNetLimit(UINT uiTotal)
{
	struct rlimit stLimit;

	memset(&stLimit, '\0', sizeof(struct rlimit));
	stLimit.rlim_max = stLimit.rlim_cur = uiTotal;

	if (MR_FAILURE == setrlimit(RLIMIT_NOFILE, &stLimit)) {
		MR_ERROR("%s\n", strerror(errno));
		return MR_FAILURE;
	}

	return MR_SUCCESS;
}

int CMrNet::MrNetSetNonBlock()
{
	if (MR_FAILURE == fcntl(m_iSocket, F_SETFL, fcntl(m_iSocket, F_GETFL, 0) | O_NONBLOCK)) {
		MR_ERROR("%s\n", strerror(errno));
		return MR_FAILURE;
	}

	return MR_SUCCESS;
}

int CMrNet::MrNetSetReuseAddr()
{
	int iOn = 1;

	if (MR_FAILURE == setsockopt(m_iSocket, SOL_SOCKET, SO_REUSEADDR, &iOn, sizeof(iOn))) {
		MR_ERROR("%s\n", strerror(errno));
		return MR_FAILURE;
	}

	return MR_SUCCESS;
}

int CMrNet::MrNetSetSndBuf(UINT uiSize)
{
	if (MR_FAILURE == setsockopt(m_iSocket, SOL_SOCKET, SO_SNDBUF, &uiSize, sizeof(uiSize))) {
		MR_ERROR("%s\n", strerror(errno));
		return MR_FAILURE;
	}

	return MR_SUCCESS;
}

int CMrNet::MrNetSetRcvBuf(UINT uiSize)
{
	if (MR_FAILURE == setsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, &uiSize, sizeof(uiSize))) {
		MR_ERROR("%s\n", strerror(errno));
		return MR_FAILURE;
	}

	return MR_SUCCESS;
}

void CMrNet::MrNetSetTimeOut(int iSec, int iUsec)
{
	struct timeval stTime;

	stTime.tv_sec = iSec;
	stTime.tv_usec = iUsec;

	if (MR_FAILURE == setsockopt(m_iSocket, SOL_SOCKET, SO_SNDTIMEO, &stTime, sizeof(stTime))) {
		MR_ERROR("%s\n", strerror(errno));
	}

	if (MR_FAILURE == setsockopt(m_iSocket, SOL_SOCKET, SO_RCVTIMEO, &stTime, sizeof(stTime))) {
		MR_ERROR("%s\n", strerror(errno));
	}

	return;
}
